<template>
  <view class="region-picker-container">
    <!-- 显示区域的插槽，可自定义显示内容 -->
    <slot name="display" :region="region" :regionString="regionString" :openPicker="openPicker">
      <view
        @click="openPicker"
        class="w-full px-[24rpx] py-[20rpx] min-h-[84rpx] text-[28rpx] placeholder-gray-400 border border-gray-300 rounded-[8rpx] box-border bg-[#eee]"
      >
        {{ regionString || '请选择地址' }}
      </view>
    </slot>

    <!-- 选择器组件 -->
    <nut-cascader
      v-model:visible="showPicker"
      v-model="region"
      text-key="name"
      value-key="name"
      title="选择地址"
      :options="options"
      @change="handleChange"
    >
      <!-- 可自定义选择器头部内容 -->
      <template #header>
        <slot name="header">
          <view class="flex justify-between items-center px-4 py-3 border-b">
            <text class="text-lg font-bold">选择地址</text>
          </view>
        </slot>
      </template>
    </nut-cascader>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, defineProps, defineEmits, onMounted } from 'vue';
import Taro from '@tarojs/taro';

// 定义组件 props
const props = defineProps({
  // 默认选中的地区
  defaultRegion: {
    type: Array as () => string[],
    default: () => ['天津市', '市辖区', '南开区']
  },
  // 是否禁用选择器
  disabled: {
    type: Boolean,
    default: false
  },
  // 自定义地区数据
  options: {
    type: Array,
    required: false
  }
});

// 定义组件 emits
const emits = defineEmits(['change', 'open', 'close']);

// 状态管理
const showPicker = ref(false);
const region = ref(props.defaultRegion);
const options = ref(props.options || []);

// 计算属性：将选中的地区转为字符串
const regionString = computed(() => {
  return region.value.length > 0 ? region.value.join(' ') : '';
});

// 监听 props 变化，更新地区数据
watch(() => props.options, (newOptions) => {
  if (newOptions && newOptions.length > 0) {
    options.value = newOptions;
  }
});

// 监听默认地区变化
watch(() => props.defaultRegion, (newDefault) => {
  if (newDefault && newDefault.length > 0) {
    region.value = [...newDefault];
  }
});

// 打开选择器
const openPicker = () => {
  if (props.disabled) return;
  showPicker.value = true;
  emits('open');
};

// 处理地区选择变化
const handleChange = (value: string[]) => {
  region.value = value;
  emits('change', value);
};

// 监听选择器显示状态变化
watch(showPicker, (newVal) => {
  if (!newVal) {
    emits('close');
  }
});

// 组件挂载时获取地区数据
const fetchRegionData = async () => {
  try {
    if (!props.options || props.options.length === 0) {
      // 如果没有传入自定义数据，则从API获取
      const res = await Taro.request({
        url: '/city',
        method: 'GET'
      });
      options.value = res.data;
    } else {
      // 使用传入的自定义数据
      options.value = props.options;
    }
  } catch (error) {
    console.error('获取地区数据失败:', error);
  }
};

// 初始化
const init = () => {
  fetchRegionData();
};

// 组件挂载时初始化
onMounted(() => {
  init();
});
</script>

<style scoped lang="scss">
.region-picker-container {
  position: relative;
  width: 100%;
}
</style>
